package cn.aiweiyi.qingjing.coupon.template.controller;

import cn.aiweiyi.qingjing.coupon.comm.exception.CouponException;
import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.rmi.MarshalledObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 青衿
 * @Date 2020/11/17 14:02
 * 健康检查控制器
 **/
@Slf4j
@RestController
public class HealthController {
    //服务发现客户端
    @Autowired
    private DiscoveryClient client;

    //服务注册接口,提供了获取服务id的方法
    @Qualifier("eurekaRegistration")
    @Autowired
    private Registration registration;

    @GetMapping("/health")
    public String health() {
        log.debug("健康测试");
        return "模板微服务运行正常!";
    }


    /**
     * 异常测试接口
     * 127.0.0.1:7001/coupon-template/exception
     */
    @GetMapping("/exception")
    public String exception() throws CouponException {
        log.debug("异常测试");
        throw new CouponException("Coupon Template抛出了异常!");
    }

    /**
     * 获取 Eureka Server上的本微服务实例的元信息
     * 127.0.0.1:7001/coupon-template/info
     */
    @GetMapping("/info")
    public List<Map<String, Object>> info() {
        //大约需要等待两分钟时间才能获取到注册信息
        List<ServiceInstance> instances =
                client.getInstances(registration.getServiceId());

        List<Map<String, Object>> result =
                new ArrayList<>(instances.size());
        instances.forEach(i -> {
            Map<String, Object> info = new HashMap<>();
            info.put("serviceId", i.getServiceId());
            info.put("instanceId", i.getInstanceId());
            info.put("port", i.getPort());
            result.add(info);
        });
        return result;
    }

}
